package com.sright.bcard.user.biz.manager.impl;

import com.sright.bcard.common.service.share.exception.base.BusinessErrorException;
import com.sright.bcard.common.service.share.exception.code.BusinessCode;
import com.sright.bcard.common.service.share.utils.BcryptUtils;
import com.sright.bcard.common.service.share.utils.SaltUtils;
import com.sright.bcard.user.biz.manager.AdminManager;
import com.sright.bcard.user.dal.dao.AdminDAO;
import com.sright.bcard.user.dal.entity.AdminDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author peter
 * @description
 * @date 2020/5/25
 */
@Component
public class AdminManagerImpl implements AdminManager {

    @Autowired
    private AdminDAO adminDAO;

    @Override
    public Boolean updateAdminPassword(String oldPassword, String newPassword, Long userId) {
        if (userId == null) {
            throw new BusinessErrorException(BusinessCode.ACCOUNT_NOT_EXIST);
        }
        AdminDO adminDO = adminDAO.selectById(userId);
        if (adminDO == null) {
            throw new BusinessErrorException(BusinessCode.ACCOUNT_NOT_EXIST);
        }
        boolean oldPasswordStatus = BcryptUtils.checkpw(oldPassword + "&" + adminDO.getSalt(),adminDO.getPassword());
        if (!oldPasswordStatus) {
            throw new BusinessErrorException(BusinessCode.ACCOUNT_OR_PWD_ERROR);
        }
        //生成6位盐
        String salt = SaltUtils.getSalt(6);
        String newHashPassword = BcryptUtils.hashpw(newPassword + "&" + salt);

        AdminDO adminDOUpdate = new AdminDO();
        adminDOUpdate.setId(userId);
        adminDOUpdate.setSalt(salt);
        adminDOUpdate.setPassword(newHashPassword);
        return adminDAO.updateSelective(adminDOUpdate);
    }

    @Override
    public Integer updateDayFirstLogin() {
        Integer result = adminDAO.updateDayFirstLogin();
        return result;
    }
}
